package chen.web.controller.blog;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.controller.blog.form.SignUpForm;
import chen.web.controller.forum.JSONError;
import chen.web.controller.forum.JSONResponse;
import chen.web.user.Account;
import chen.web.user.AccountManager;
import chen.web.user.EmailAlreadyBeenRegisteredException;
import chen.web.user.NicknameAlreadyBeenRegisteredException;

@Controller
public class Signup {

	private @Autowired Validator validator;
	private @Autowired AccountManager am;
	
	@RequestMapping(value="/signup", method=RequestMethod.POST)
	public @ResponseBody JSONResponse signUp(@RequestBody SignUpForm bean){
		Set<ConstraintViolation<SignUpForm>> failures = validator.validate(bean);
		if (!failures.isEmpty()) {
			return JSONResponse.invalid(failures);
		} 
		
		JSONResponse res = JSONResponse.successed();
		try {
			Account account = am.register(bean.getEmail(), bean.getPassword(), bean.getEmail());
			res.setReturnObject(account);
		} catch (NicknameAlreadyBeenRegisteredException e) {
			// TODO Auto-generated catch block
			res.addError(JSONError.create("email", "email已经被注册"));
		} catch (EmailAlreadyBeenRegisteredException e) {
			// TODO Auto-generated catch block
			res.addError(JSONError.create("email", "email已经被注册"));
		}
		return res;
	}
	
	@RequestMapping(value="/signup", method=RequestMethod.GET)
	public String signUp(){
		return "signup";
	}

}
